package utils;

import org.springframework.core.io.Resource;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class DownloadUtils {

    public static void downloadZipFile(String url, String destFilePath) throws IOException {
        File file = new File(destFilePath).getParentFile();
        if (!file.exists()) {
            file.mkdirs();
        }
        RestTemplate restTemplate = new RestTemplate();

        // 发送 GET 请求获取文件
        ResponseEntity<Resource> response = restTemplate.exchange(url, HttpMethod.GET, null, Resource.class);

        // 获取输入流
        Resource resource = response.getBody();
        if (resource == null) {
            throw new IOException("Failed to retrieve resource");
        }

        try (InputStream inputStream = resource.getInputStream();
             OutputStream outputStream = new FileOutputStream(destFilePath)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }
}
